﻿using System;
using System.Collections.Generic;
using System.Linq;

using Aden.Util.Common;
using Aden.Model.Common;
using Aden.Model.Stock;

namespace Aden.DAL.StockData
{
    public class Stockout: StockTransfer
    {
        public Stockout(string appGuid, string costCenterCode, string orderDate, string createUser)
           : this(appGuid,costCenterCode,  "", orderDate, createUser){ }

        public Stockout(string appGuid,string costCenterCode,string businessType, string orderDate, string createUser)
            : base(appGuid, costCenterCode,  businessType, orderDate,  createUser) {}
        
        public override List<Dictionary<string,object>> GetDates()
        {
            return base.GetDates();
        }

        public virtual void save(List<TransData> data, List<SQL> othsql)
        {
            base.save(data, TransTypes.Stockout, othsql);
        }

        public override Dictionary<string,object> save(StockParam param) //Dictionary<string, string> param, List<TransData> data
        {
            try
            {
                base.save(param.data, TransTypes.Stockout);
                return null;
            }
            catch(Exception e)
            {
                List<Dictionary<string, object>> items = GetItems();
                if (items == null || !items.Any()) throw e;
                List<string> keys = items.FirstOrDefault().Keys.ToList();
                if (!keys.Contains("qty")) keys.Add("qty");
                
                return new Dictionary<string, object>()
                {
                    { "Error", e.Message },
                    {"data",  param.data.GroupJoin(items, a => a.itemCode.ToStringTrim(), b => b["itemCode"].ToStringTrim(),
                        (a, b) => {
                            Dictionary<string,object> dic = null;
                            //服务产品不考虑库存
                            if((a.isServiceItem) || b== null || !b.Any())
                            {
                                dic = a.ToDictionary(keys.ToArray());
                                dic.Remove("stockQty");
                                return dic;
                            }

                            dic = b.FirstOrDefault();
                            if(a.qty != 0)
                            {
                                if(dic.ContainsKey("qty"))
                                    dic["qty"] = a.qty;
                                else
                                    dic.Add("qty",a.qty);
                            }
                            return dic;
                        }).ToList()
                    }
                };
            }
        }

       
    }
}
